package com.fafu.control;

import com.fasterxml.jackson.annotation.JsonBackReference;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import util.Dictionary;
import util.JsonRsp;
import util.VerifyCodeUtils;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.ZoneId;

import static util.Dictionary.CODE.SUCCESS;
import static util.Dictionary.CODE.VALIDATE_CODE_ERROR;

@Api("工具接口")
@Controller
@RequestMapping("/verify")
public class VerifyCodeControl {
    private Logger logger = LoggerFactory.getLogger(VerifyCodeControl.class);
    @ApiOperation("获取验证码")
    @RequestMapping(value = "/getVerifyCode", method = RequestMethod.GET)
    public void getVerifyCode(HttpServletRequest request, HttpServletResponse response){
        try{
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/jpeg");
            // 生成随机字串
            String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
            // 存入会话session
            HttpSession session = request.getSession(true);
            // 删除以前的
            session.removeAttribute("verCode");
            session.removeAttribute("codeTime");
            session.setAttribute("verCode", verifyCode.toLowerCase());
            session.setAttribute("codeTime", LocalDateTime.now());
            // 生成图片
            int w = 100, h = 30;
            OutputStream out = response.getOutputStream();
            VerifyCodeUtils.outputImage(w, h, out, verifyCode);

        }catch (Exception e){
            logger.error(""+e);
        }
    }
    @ApiOperation("获取验证码")
    @ResponseBody
    @RequestMapping(value = "/validCode", method = RequestMethod.GET)
    public JsonRsp validCode(
            @RequestParam("code")@ApiParam("验证码")String code
            ,HttpServletRequest request){
        try{
            HttpSession session = request.getSession();
            Object verCode = session.getAttribute("verCode");
            if (null == verCode)
                return JsonRsp.fail(VALIDATE_CODE_ERROR,"验证码已失效，请重新输入");
            String verCodeStr = verCode.toString();
            LocalDateTime localDateTime = (LocalDateTime)session.getAttribute("codeTime");
            long past = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
            long now = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
            if(verCodeStr == null || code == null || code.isEmpty() || !verCodeStr.equalsIgnoreCase(code)){
                return JsonRsp.fail(VALIDATE_CODE_ERROR,"验证码错误");
            } else if((now-past)/1000/60>5){
                return JsonRsp.fail(VALIDATE_CODE_ERROR,"验证码已过期，重新获取");
            } else {
                //验证成功，删除存储的验证码
                session.removeAttribute("verCode");
                return JsonRsp.success(SUCCESS,"success");
            }
        }catch(Exception e){
            logger.error(""+e);
            return JsonRsp.fail(Dictionary.CODE.SYSTEM_ERROR,"system error");
        }
    }



}
